package {{package}};

import io.helidon.security.EndpointConfig;
import io.helidon.security.SecurityContext;
import io.helidon.webclient.http1.Http1Client;
import io.helidon.webclient.security.WebClientSecurity;
import io.helidon.webserver.WebServer;
import io.helidon.webserver.http.HttpRules;
import io.helidon.webserver.http.HttpService;
import io.helidon.webserver.http.ServerRequest;
import io.helidon.webserver.http.ServerResponse;

final class JwtOverrideService implements HttpService {

    private final Http1Client client = Http1Client.builder()
            .addService(WebClientSecurity.create())
            .build();

    @Override
    public void routing(HttpRules rules) {
        rules.get("/override", this::override)
                .get("/propagate", this::propagate);
    }

    private void override(ServerRequest req, ServerResponse res) {
        SecurityContext context = req.context()
                .get(SecurityContext.class)
                .orElseThrow(() -> new RuntimeException("Security not configured"));

        WebServer server = req.context()
                .get(WebServer.class)
                .orElseThrow(() -> new RuntimeException("WebServer not found in context"));

        String result = client.get("http://localhost:" + server.port("backend") + "/hello")
                .property(EndpointConfig.PROPERTY_OUTBOUND_ID, "jill")
                .requestEntity(String.class);

        res.send("You are: " + context.userName() + ", backend service returned: " + result);
    }

    private void propagate(ServerRequest req, ServerResponse res) {
        SecurityContext context = req.context()
                .get(SecurityContext.class)
                .orElseThrow(() -> new RuntimeException("Security not configured"));

        WebServer server = req.context()
                .get(WebServer.class)
                .orElseThrow(() -> new RuntimeException("WebServer not found in context"));

        String result = client.get("http://localhost:" + server.port("backend") + "/hello")
                .requestEntity(String.class);

        res.send("You are: " + context.userName() + ", backend service returned: " + result);
    }
}
